package com.wzy.webuserdemo.controller;

import com.wzy.webuserdemo.pojo.Dept;
import com.wzy.webuserdemo.pojo.User;
import com.wzy.webuserdemo.service.DeptService;
import com.wzy.webuserdemo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private DeptService deptService;

    //负责跳转到首页
    @GetMapping("/toIndex")
    public String toIndex() {
        return "index";
    }

    @GetMapping("/list")
    public String queryUserList(Model model){
        List<User> userList = userService.queryUserList();
        model.addAttribute("users",userList);
        return "list";
    }

    @GetMapping("/add")
    public String toAdd(Model model) {
        //查询所有的部门，在add.html页面中进行显示
        List<Dept> deptList = deptService.queryAllDept();
        model.addAttribute("depts", deptList);
        return "add";
    }

    @PostMapping("/save")
    public String addSave(User user){
        boolean success = userService.insertUser(user);
        if (success) {
            return "redirect:/user/list"; //"forward:"
        } else {
            return "redirect:/add"; //新增失败就又跳回到新增页面
        }
    }

    @GetMapping("/modify/{id}")
    public String toUpdatePage(@PathVariable("id") Long id , Model model){
        //1、根据用户ID查询用户的详细对象信息
        User user = userService.getById(id);
        //2、查询所有的部门，在add.html页面中进行显示
        List<Dept> deptList = deptService.queryAllDept();
        //3、保存数据
        model.addAttribute("user", user);
        model.addAttribute("depts", deptList);
        //4、跳转到用户修改页面(add.html是一个修改添加二合一的页面)
        return "add";
    }

    //用户修改
    @PutMapping("/save")
    public String updateUser(User user) {
        boolean isFlag = userService.updateUser(user);
        if (isFlag) {
            return "redirect:/user/list"; //"forward:"
        } else {
            //修改失败就又跳回到修改页面
            return "redirect:/modify/"+user.getId();
        }
    }
    @DeleteMapping("/delete/{id}")
    public String delUser(@PathVariable("id") long id) {
        boolean isFlag = userService.delUser(id);
        if (isFlag) {
            return "redirect:/user/list";
        } else {
            return "redirect:/user/list";
        }
    }

}
